#include <QPainter>
#include <QKeyEvent>
#include <QDebug>
#include "widget.h"

const int roundRadius = 10;
const int margin = 30;


Widget::Widget(QWidget *parent)
    : QWidget(parent), anima(this), ground(anima.ground), column1(anima.column1), column2(anima.column2), ball(anima.ball)
{
    setMinimumWidth(400);
    setMinimumHeight(400);
    resize(400, 400);

    // 坐标初始化
    updateWall();
    ball.frame.moveTopLeft(QPoint(ground.center().x() - ball.radius, ground.y() - ball.radius * 2));

    // 刷新画面
    void (Widget::*fn)() = &Widget::update;
    connect(&anima, &MyAnimation::valueChanged, this, fn);

    anima.start();

}

Widget::~Widget()
{

}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);

    painter.drawRect(ground);
    painter.drawRoundedRect(column1, roundRadius, roundRadius);
    painter.drawRoundedRect(column2, roundRadius, roundRadius);

    painter.setBrush(Qt::red);
    painter.drawEllipse(ball.frame);

}

void Widget::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event)
    updateWall();

}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Left)
        ball.pushLeft();
    if (event->key() == Qt::Key_Right)
        ball.pushRight();
    qInfo() << ball.sumOfComponentsAcc();
}

void Widget::updateWall()
{
    ground = QRect(this->rect().bottomLeft() * 2 / 3, this->rect().bottomRight());
    QRect column;
    column.setSize(QSize(40, this->height() / 4));
    column.moveBottomLeft(ground.topLeft() + QPoint(margin, roundRadius));
    column1 = column;
    column.moveBottomRight(ground.topRight() + QPoint(-margin, roundRadius));
    column2 = column;
    ball.frame.moveTopLeft(QPoint(ball.frame.x(), ground.y() - ball.radius * 2));
}


